package capteurs;

import java.util.ArrayList;
import java.util.Observable;

import rails.Rail;
import train.Train;

public class CPresence extends Capteur {
	public CPresence() {
		super();
	}
	
	public CPresence(Rail rail, int troncon) {
		super(rail, troncon);
	}
	
	private void notify_all(boolean presence) {
		for(int i=0; i < list.size(); ++i) {
			list.get(i).onPresenceChange(this, presence);
		}
	}
	
	public void update(Observable arg0, Object arg1) {
		ArrayList<Train> tListe = rail.getTrains();
		Train tmpTrain;
		
		for(int i=0; i < tListe.size(); ++i) {
			tmpTrain = tListe.get(i);
			if(tmpTrain.getDirection()) {
				if(troncon <= tmpTrain.getCurrPosOnRail() && troncon > tmpTrain.getCurrPosOnRail() - tmpTrain.getSize()) {
					if(!hasTrain) {
						hasTrain = true;
						notify_all(true);
						System.out.println("J'ai notify ! " + troncon + " postrain " + tmpTrain.getCurrPosOnRail());
					}
					return;
				}
			}
			else {
				if(troncon >= tmpTrain.getCurrPosOnRail() && troncon < tmpTrain.getCurrPosOnRail() + tmpTrain.getSize()) {
					if(!hasTrain) {
						hasTrain = true;
						notify_all(true);
						System.out.println("J'ai notify ! " + troncon + " postrain " + tmpTrain.getCurrPosOnRail());
					}
					return;
				}
			}
		}
		
		if(hasTrain) {
			System.out.println("J'ai notify false !");
			hasTrain = false;
			notify_all(false);
		}
	}
	
	public String toString() {
		return "Je suis un capteur de presence";
	}
}
